package com.atguigu.gmall.activity.task;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author luYinLei
 * @version 1.0
 * @date 2021/7/15 10:04
 */
@Component
public class SeckillTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0/15 * * * * * ")
    public void seckillIntoRedisTask() {
        //获取五个时间段
        List<Date> dateMenus = DateUtil.getDateMenus();
        //遍历循环
        for (Date dateMenu : dateMenus) {
            //获取开始时间
            String startTime = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYY_MM_DDHHMM);
            //计算结束时间段时间
            Date date = DateUtil.addDateHour(dateMenu, 2);
            String endTime = DateUtil.data2str(date, DateUtil.PATTERN_YYYYMMDDHH);
            //拼接条件
            LambdaQueryWrapper<SeckillGoods> wrapper = new LambdaQueryWrapper<>();
            //审核状态
            wrapper.eq(SeckillGoods::getStatus,1);
            //判断是否符合时间段 startTime=<开始时间 结束时间<endTime
            wrapper.ge(SeckillGoods::getStartTime,startTime);
            wrapper.le(SeckillGoods::getEndTime,endTime);
            //判断库存是否大于0
            wrapper.gt(SeckillGoods::getStockCount,0);
            //如果redis没有这个数据
            String key = DateUtil.data2str(dateMenu, DateUtil.PATTERN_YYYYMMDDHH);
            Set keys = redisTemplate.boundHashOps("SeckillGoods_" + key).keys();
            if (keys!=null && keys.size()>0){
                wrapper.notIn(SeckillGoods::getId,keys);
            }
            //查询数据库信息
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectList(wrapper);
            //遍历循环
            for (SeckillGoods seckillGood : seckillGoods) {
                //存入redis
                redisTemplate.boundHashOps("SeckillGoods_" + key).put(seckillGood.getId(),seckillGood);
            }
        }
    }

}
